package com.banciyuan.bcywebview.biz.report;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.CoserApi;
import com.banciyuan.bcywebview.api.DailyApi;
import com.banciyuan.bcywebview.api.GroupApi;
import com.banciyuan.bcywebview.api.IllustApi;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.api.ZhipinApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.utils.constants.MyConstants;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by hy on 2016/2/1.
 */
public class ReportActivity extends BaseActivity implements View.OnClickListener {
    private RadioGroup rgReport;
    private EditText etReportContent;
    private ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private RequestQueue mQueue;
    private String urlAction = "";
    private List<BcyPair> pairList;
    private TextView tvReport;

    private int report_type = 0;//0,作品举报；1，评论举报；2，小组话题举报 3.回复举报
    private String reply_id = "";
    private String comment_id = "";
    private String gid = "";

    private String[] reportTypes;
    private String currentType = "";
    private String reportReson = "";

    private boolean is_post;
    private int timelineIndex;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.report_layout);
        initArgs();
        initUi();
        initActionbar();
        initAction();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        reportTypes = getResources().getStringArray(R.array.report_type);
        currentType = reportTypes[0];
        Intent intent = getIntent();
        report_type = intent.getIntExtra(gotoUtil.INTENT_VALUE_ONE, 0);
        reply_id = intent.getStringExtra(gotoUtil.INTENT_VALUE_TWO);
        comment_id = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        gid = intent.getStringExtra(gotoUtil.INTENT_VALUE_THREE);
        timelineIndex = intent.getIntExtra(gotoUtil.INTENT_VALUE_FIVE, -1);
        switch (report_type) {
            case 0:
            case 1:
            case 3:
                getBaseDetailVaule(intent);
                break;
            case 2:
                getGroupValue();
                break;
        }
    }

    private void getGroupValue() {
        pairList = new ArrayList<>();
        pairList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        pairList.add(new BcyPair(HttpUtils.GID, gid));
        urlAction = GroupApi.getDenouncegroup();
    }

    public void getBaseDetailVaule(Intent intent) {

        int timelineType = intent.getIntExtra(MyConstants.TIMELINETYPE, 0);
        pairList = new ArrayList<>();
        pairList.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(this).getToken()));
        switch (timelineType) {
            case TimelineFactory.TIMELINE_TYPE_COSER:
                pairList.add(new BcyPair(HttpUtils.RPID, intent.getStringExtra(MyConstants.RPIDVALUE)));
                pairList.add(new BcyPair(HttpUtils.CPID, intent.getStringExtra(MyConstants.CPIDVALUE)));
                setReportUrlAction(CoserApi.getDenouncepost(), CoserApi.getDenouncereply(), CoserApi.getDenounceComment());
                break;
            case TimelineFactory.TIMELINE_TYPE_ILLUST:
                pairList.add(new BcyPair(HttpUtils.RPID, intent.getStringExtra(MyConstants.RPIDVALUE)));
                pairList.add(new BcyPair(HttpUtils.DPID, intent.getStringExtra(MyConstants.DPIDVALUE)));
                setReportUrlAction(IllustApi.getDenouncepost(), IllustApi.getDenouncereply(), IllustApi.getDenounceComment());
                break;
            case TimelineFactory.TIMELINE_TYPE_DAILY:
                pairList.add(new BcyPair(HttpUtils.UDID, intent.getStringExtra(MyConstants.UDIDVALUE)));
                setReportUrlAction(DailyApi.getDenouncepost(), DailyApi.getDenouncereply(), DailyApi.getDenounceComment());
                break;
            case TimelineFactory.TIMELINE_TYPE_GROUP:
                pairList.add(new BcyPair(HttpUtils.GID, intent.getStringExtra(MyConstants.GIDVALUE)));
                pairList.add(new BcyPair(HttpUtils.POSTID, intent.getStringExtra(MyConstants.POSTIDVALUE)));
                setReportUrlAction(GroupApi.getDenouncepost(), GroupApi.getDenouncereply(), GroupApi.getDenounceComment());
                break;
            case TimelineFactory.TIMELINE_TYPE_WRITER:
                pairList.add(new BcyPair(HttpUtils.RPID, intent.getStringExtra(MyConstants.RPIDVALUE)));
                pairList.add(new BcyPair(HttpUtils.WPID, intent.getStringExtra(MyConstants.WPIDVALUE)));
                setReportUrlAction(NovelApi.getDenouncepost(), NovelApi.getDenouncereply(), NovelApi.getDenounceComment());
                break;
            case TimelineFactory.TIMELINE_TYPE_GOODS:
                pairList.add(new BcyPair(HttpUtils.ZGID, intent.getStringExtra(MyConstants.ZGIDVALUE)));
                setReportUrlAction(ZhipinApi.getDenouncePost(), ZhipinApi.getDenouncePost(), ZhipinApi.getDenouncePost());
                break;
            default:
                break;
        }
    }

    private void setReportUrlAction(String postUrl, String commentUrl, String childCommentUrl) {
        switch (report_type) {
            case 0:
                urlAction = postUrl;
                break;
            case 1:
                urlAction = commentUrl;
                pairList.add(new BcyPair(HttpUtils.COMMENT_ID, reply_id));
                break;
            case 3:
                urlAction = childCommentUrl;
                pairList.add(new BcyPair(HttpUtils.COMMENT_ID, reply_id));
                if (!TextUtils.isEmpty(comment_id))
                    pairList.add(new BcyPair(HttpUtils.REPLY_ID, comment_id));
                break;
        }
    }


    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.report_reason));
    }

    @Override
    protected void initUi() {
        rgReport = (RadioGroup) findViewById(R.id.rg_report);
        etReportContent = (EditText) findViewById(R.id.et_report_content);
        tvReport = (TextView) findViewById(R.id.tv_report);
    }

    @Override
    protected void initAction() {
        tvReport.setOnClickListener(this);
        rgReport.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_ads_rubbish:
                        etReportContent.setVisibility(View.GONE);
                        tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_pink_bigtwo);
                        break;
                    case R.id.rb_political_content:
                        etReportContent.setVisibility(View.GONE);
                        tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_pink_bigtwo);
                        break;
                    case R.id.rb_unfriendly_content:
                        etReportContent.setVisibility(View.GONE);
                        tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_pink_bigtwo);
                        break;
                    case R.id.rb_illegal_content:
                        etReportContent.setVisibility(View.GONE);
                        tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_pink_bigtwo);
                        break;
                    case R.id.rb_copy_others:
                        etReportContent.setVisibility(View.VISIBLE);
                        changeReportButtonBackground();
                        break;
                    case R.id.rb_others:
                        etReportContent.setVisibility(View.VISIBLE);
                        changeReportButtonBackground();
                        break;
                }
            }
        });
        etReportContent.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                changeReportButtonBackground();
            }
        });
    }

    private void changeReportButtonBackground() {
        if (TextUtils.isEmpty(etReportContent.getText().toString().trim())) {
            tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_grey_bigtwo);
        } else {
            tvReport.setBackgroundResource(R.drawable.shape_timeline_bg_pink_bigtwo);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_report:
                if (judgeLogin() && judgeReportType())
                    report();
                break;
        }
    }

    private boolean judgeLogin() {
        if (!UserDataHelper.ifLogin(this)) {
            MyToast.show(this, getString(R.string.loginfirst));
            return false;
        }
        return true;
    }

    private boolean judgeReportType() {
        switch (rgReport.getCheckedRadioButtonId()) {
            case R.id.rb_ads_rubbish:
                currentType = reportTypes[0];
                reportReson = "";
                return true;
            case R.id.rb_political_content:
                currentType = reportTypes[1];
                reportReson = "";
                return true;
            case R.id.rb_unfriendly_content:
                currentType = reportTypes[2];
                reportReson = "";
                return true;
            case R.id.rb_illegal_content:
                currentType = reportTypes[3];
                reportReson = "";
                return true;
            case R.id.rb_copy_others:
                currentType = reportTypes[4];
                return isReportResonEmpty();
            case R.id.rb_others:
                currentType = reportTypes[5];
                return isReportResonEmpty();
            default:
                return false;
        }
    }

    private boolean isReportResonEmpty() {
        reportReson = etReportContent.getText().toString().trim();
        return !TextUtils.isEmpty(reportReson);
    }

    public void report() {
        if (is_post) return;
        is_post = true;
        String url = HttpUtils.BASE_URL + urlAction;
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.addAll(pairList);
        paramsList.add(new BcyPair("type", currentType));
        if (!TextUtils.isEmpty(reportReson)) {
            paramsList.add(new BcyPair("reason", reportReson));
        }
        Map<String, String> map = HttpUtils.getData(paramsList);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                rgReport.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        is_post = false;
                    }
                }, 200);
                if (StatusCodeUtils.dealStatusCode(s, ReportActivity.this)) {
                    try {
                        JSONObject result = new JSONObject(s);
                        String data = result.getString(HttpUtils.UPLOAD_DATA);
                        MyToast.show(ReportActivity.this, data);
                        BaseObserver.getInstance().notifyWatchers(BaseObserver.REPORT_SUCCESS, timelineIndex);
                        finish();
                    } catch (JSONException e) {
                        MyToast.show(ReportActivity.this, getString(R.string.report_error));
                        finish();
                    }
                } else {
                    MyToast.show(ReportActivity.this, getString(R.string.report_error));
                    finish();
                }


            }
        };
        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                rgReport.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        is_post = false;
                    }
                }, 200);
                MyToast.show(ReportActivity.this, getString(R.string.report_error));
                finish();

            }
        };
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(stringRequestParam);
    }

}